package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeifnClient;

import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zipkin2.reporter.amqp.RabbitMQSender;

import java.sql.Date;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * ClassName: AlipayServiceImpl
 * Package: com.atguigu.gmall.payment.service.impl
 * Description:
 *
 * @Author 刘轩
 * @Create 2023-09-05 21:16
 * @Version 1.0
 */

@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private OrderFeifnClient orderFeifnClient;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private RabbitService rabbitService;
    /**
     * 生成支付二维码
     *
     * @param orderId
     * @return
     */
    @Override
    public String createAlipay(Long orderId) {
        //  根据订单Id 获取订单对象
        OrderInfo orderInfo = orderFeifnClient.getOrderInfo(orderId);
        //  必须在订单有效期内。
        if ("PAID".equals(orderInfo.getOrderStatus()) || "CLOSED".equals(orderInfo.getOrderStatus())) {
            return "当前订单" + orderId + "已关闭或支付";
        }
        //  保存当前支付的交易记录. 如果要想控制只能一种支付方式，setnx orderId 1 ---> del key;
        paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());
        //	生成客户端 将这个对象封装到spring 容器中.
        //  AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        //	生成请求对象
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(AlipayConfig.notify_payment_url);
        //同步跳转地址，仅支持http/https
        request.setReturnUrl(AlipayConfig.return_payment_url);
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性 在生成订单的时候，制作过outTradeNo
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        //支付金额，最小值0.01元
        bizContent.put("total_amount", 0.01);
        //订单标题，不可使用特殊符号
        bizContent.put("subject", "测试商品");
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        /******可选参数******/
        /*
        if orderInfo.getExpireTime()> date
            10分
        else
            否则订单的失效时间
        DateUtil.dateCompare();
         */
        ZonedDateTime dateTime = LocalDateTime.now().plusMinutes(10).atZone(ZoneId.systemDefault());
        //  Date
        //  Instant instant = LocalDateTime.now().plusMinutes(10).atZone(ZoneId.systemDefault()).toInstant();
        //  java.util.Date date = Date.from(instant);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println("时间：" + dateTime.format(dateTimeFormatter));
        //  二维码过期时间 考虑二维码的失效时间到底给多少?
        bizContent.put("time_expire", dateTime.format(dateTimeFormatter));
        /*
        <html>
        <title></title>
        <body>
            <form>
                <input type=text>
                <input type=text>
            </form>
        </body>
        </html>

         */
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        //  返回数据
        return response.getBody();

    }

    /**
     * 发起退款
     * @param orderId
     * @return
     */
    @Override
    public Boolean refund(Long orderId) {
        // 获取订单id
        OrderInfo orderInfo = orderFeifnClient.getOrderInfo(orderId);
        if(orderInfo == null) return null;
        // 直接俄从spring 容器中获取
       // AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        // 创建退款请求对象
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        // 只能查询paymentInfo
       // bizContent.put("trade_no", "2021081722001419121412730660");
        // orderInfo ,paymentInfo;
        bizContent.put("out_trade_no",orderInfo.getOutTradeNo() );
        bizContent.put("refund_amount", 0.01); // 写死退款金额
       //  bizContent.put("out_request_no", "HZ01RF001");


        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response =alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            // 修改状态。。。只要返回true、就表示退款成功
            if("Y".equals(response.getFundChange())) {
                // 跟新数据
                PaymentInfo paymentInfoUpd = new PaymentInfo();
                paymentInfoUpd.setPaymentStatus(PaymentStatus.CLOSED.name());
                paymentService.upDatePaymentInfoStatus(orderInfo.getOutTradeNo(),PaymentType.ALIPAY.name(),paymentInfoUpd );
                // 退款时关闭订单
                this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_ORDER_CLOSED,MqConst.ROUTING_ORDER_CLOSED,orderId);
                return true;
            }
            return false;
        } else {
            System.out.println("调用失败");
            return false;
        }


    }
    /**
     * 关闭支付宝支付记录
     * @param orderId
     * @return
     */
    @Override
    public Boolean closeAlipay(Long orderId)  {
        // 获取订单对象
        OrderInfo orderInfo = orderFeifnClient.getOrderInfo(orderId);
        if(orderInfo == null) return false;
        // AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
         // 创意交易关闭对象
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }


    /**
     * 查看是否有交易记录
     * @param orderId
     * @return
     */
    @Override
    public boolean checkPayment(Long orderId) {
        OrderInfo orderInfo = orderFeifnClient.getOrderInfo(orderId);
        if(orderInfo == null) return false;
        // AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        // 创建查询请求条件
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no",orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        // 调用方法
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
//            if("WAIT_BUYER_PAY".equals(response.getTradeStatus())){
//                // 说明扫码，等待付款，true；
//            }else if ("TRADE_CLOSED".equals(response.getTradeStatus()) || "tRADE_FINISHED".equals((response.getTradeStatus()))){
//                // 说明交易关闭，true；
//            }else if("TRADE_SUCCESS".equals(response.getTradeStatus())){
//                // 交易成功
//            }else {
//                // false;
//            }
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }
}

